package com.hengmei.smallscreen.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import com.hengmei.smallscreen.R
import com.hengmei.smallscreen.base.BaseActivity
import com.hengmei.smallscreen.config.IntentKey
import com.hengmei.smallscreen.databinding.ActivityDetectionBinding
import com.hengmei.smallscreen.db.datebase.AppDatabase
import com.hengmei.smallscreen.db.entity.HistoricalRecord
import com.hengmei.smallscreen.manager.ClientManager
import com.hengmei.smallscreen.mmkv.DataRepository
import com.hengmei.smallscreen.utils.AntiShake
import com.hengmei.smallscreen.utils.ArithmeticUtil
import com.hengmei.smallscreen.utils.SerialUtils
import com.hengmei.smallscreen.utils.getTime
import com.hengmei.smallscreen.utils.log
import com.hengmei.smallscreen.utils.toast
import com.inuker.bluetooth.library.BluetoothClient
import com.inuker.bluetooth.library.Code.REQUEST_SUCCESS
import com.inuker.bluetooth.library.Constants.STATUS_CONNECTED
import com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse
import com.kongzue.dialogx.dialogs.BottomMenu
import com.kongzue.dialogx.dialogs.WaitDialog
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.UUID


/*
* 肉类水分检测界面
* */
class DetectionActivity : BaseActivity<ActivityDetectionBinding>(ActivityDetectionBinding::inflate){

    var uuid1=UUID.fromString("0003cdd0-0000-1000-8000-00805f9b0131")   //固定的蓝牙通讯协议
    var uuid2=UUID.fromString("0003cdd1-0000-1000-8000-00805f9b0131")
    var uuid3=UUID.fromString("0003cdd2-0000-1000-8000-00805f9b0131")

    private var testId = -1

    companion object {
        fun start(mainActivity: Activity) {
            mainActivity.startActivity(Intent(mainActivity,DetectionActivity::class.java))
        }
    }
    private var mClient: BluetoothClient?=null
    @SuppressLint("MissingPermission")
    override fun initView() {
        mClient = ClientManager().getClient()
        setOnClickListener(binding.buttonBack,binding.buttonStart,binding.yangpinmingcheng)

        mClient!!.connect(
            DataRepository.bleAddress
        ) { code, profile ->
            if (code == REQUEST_SUCCESS) {
                mClient!!.notify(DataRepository.bleAddress, uuid1, uuid2, object : BleNotifyResponse {
                    override fun onNotify(service: UUID, character: UUID, value: ByteArray) {
                        //ByteArray转16进制字符串
                        var str = value.joinToString("") {
                            String.format("%02X", it)
                        }
                        Log.d("Kevindata", "onResponse: "+str)
//01 05 05 1C 2E
//
//--01 04 ：样品含水量帧头
//--05 ：帧长
//--1C 2E ：16进制数，转为10进制为7214，代表当前样品含水量为72.14%
                        var btHead:Byte = 0x01
                        var btLength:Byte = 0x05
                        if(value[0]==btHead&&value[1]==btLength){

                            WaitDialog.dismiss()
                            var count1 = value[3]
                            var count2 = value[4]
                            var dataLength = (count1.toInt() and 0x00ff) * 256 + (count2.toInt() and 0x00ff)
                            var str1 = dataLength.toString()
                            var str2 = str1.substring(0,str1.length-2)
                            var str3 = str1.substring(str1.length-2,str1.length)
                            var str4 = "$str2.$str3"


                            log("肉类水分值：$str4")
                            var redStr = "0.0"

                            var waterDouble = str4.toDouble()

                            when(testId){
                                1->{
                                    redStr = DataRepository.redValue1.toString()
                                }
                                2->{
                                    redStr = DataRepository.redValue2.toString()
                                }
                                3->{
                                    redStr = DataRepository.redValue3.toString()
                                }
                                4->{
                                    redStr = DataRepository.redValue4.toString()
                                }
                            }

                            var value1 = ArithmeticUtil.additionStr(redStr,str4)

                            var valueDouble = str4.toDouble()

                            log("肉类水分红外法后：$valueDouble 红外法值：$redStr")
                            if(valueDouble >= 100.0 ||valueDouble <= 0.0){

                                value1 = "0.0"

                            }

//                            var value1 = ArithmeticUtil.additionStr(redStr,str4)
//                            multiplicationStr
                            value1 = ArithmeticUtil.multiplicationStr(value1,"1",1)
                            binding.countValue.text = "$value1%"
                            launch {

                                var sampleName =  binding.yangpinmingcheng.text.toString()
                                var tempStr = binding.tempValue.text.toString()

                                var projectNameStr = binding.etProjectName.text.toString()

                                var historyData = HistoricalRecord(0,value1,projectNameStr,sampleName,testId.toString(),tempStr,
                                    getTime(),DataRepository.inspector,DataRepository.testingUnit,DataRepository.unitInspected,DataRepository.tel,"0",""
                                )

                                AppDatabase.getDataBase()?.historyDao()?.insertHistory(historyData)
                                toast(getString(R.string.saveSuccess))
                            }

                        }

//                        01 04 05 01 86 --01 86 ：16进制数，转为10进制为390，代表当前电池电压为3.90V
                        var powerByte:Byte = 0x04
                        if(value[0]==btHead&&value[1]==powerByte){


                            var count1 = value[3]
                            var count2 = value[4]
                            var dataLength = (count1.toInt() and 0x00ff) * 256 + (count2.toInt() and 0x00ff)
//               电量范围 420 - 365,计算电量的百分比
                            var sum = 415- 365
                            var value1 = dataLength - 365
                            log("电量：$value1")
                            if(value1<0){
                                value1 = 0
                            }
                            var value2 = value1.toDouble()/sum.toDouble()
                            var value3 = value2*100
                            var value4 = value3.toInt()
                            binding.powerValue.text = "$value4%"
                        }

                    }
                    override fun onResponse(code: Int) {
                        if (code == REQUEST_SUCCESS) {
                            toast(getString(R.string.successNotification))
                            getPower()
                        } else {
                            toast(getString(R.string.failNotification))
                        }
                    }
                })
//              byte  01 06 05 04 00



            }else{
                toast(getString(R.string.bleError))
            }


        }
        mClient?.registerConnectStatusListener(DataRepository.bleAddress, bleConnectStatusListener) //注册蓝牙连接状态监听器
    }

//    监听蓝牙连接状态
    var bleConnectStatusListener = object : BleConnectStatusListener() {
        override fun onConnectStatusChanged(mac: String?, status: Int) {
            if (status == STATUS_CONNECTED) {
                toast(getString(R.string.bleConnected))
            } else if (status == STATUS_DISCONNECTED) {
                toast(getString(R.string.bleDisconnected))
            }
        }
    }

    override fun initViewEvents() {

    }

    override fun onDestroy() {
        super.onDestroy()

if(mClient!=null){
    mClient!!.unregisterConnectStatusListener(DataRepository.bleAddress, bleConnectStatusListener);
    mClient!!.unnotify(
        DataRepository.bleAddress, uuid1, uuid2
    ) { code ->
        if (code == REQUEST_SUCCESS) {

        }
    }
    mClient!!.disconnect(DataRepository.bleAddress);

}


    }

    fun getPower(){

        launch {

            var bt = IntentKey.BATTERY
            repeatForeverWithDelay(5000L){

                sendBleData(bt,object : BackData{
                    override fun callBackSuccess() {
                        log("send获取探头电量")
                    }
                })
            }

        }
    }

    suspend fun repeatForeverWithDelay(delayMillis: Long, action: suspend () -> Unit) {
        while (true) {
            action()
            delay(delayMillis)
        }
    }
    override fun onClick(v: View?) {
        super.onClick(v)
        if(AntiShake.check(v)){
            return //防止重复点击
        }
        when(v){
            binding.buttonBack->{
                finish()
            }
            binding.buttonStart->{
                /*  开始检测
                  检测流程，设定 样品， 设定温度 开始检测
                  设定样品类型  01 06 05 02 01
                  设定样品温度  01 06 05 03 96
                  测量含水量    01 06 05 01 00   */

                /*
                * 判断是否设置了 温度，及选择了样品
                * */
                if(binding.tempValue.text.toString().isEmpty()){
                    toast(getString(R.string.pleaseSetTemp))
                    return
                }
                if(binding.yangpinmingcheng.text.toString().isEmpty()){
                    toast(getString(R.string.pleaseSetSample))
                    return
                }

                var bt = IntentKey.SET_SAMPLE_TEMP

                var temp = binding.tempValue.text.toString().toDouble()

                if(temp>25||temp<5){
                    toast(getString(R.string.tempRange))
                    return
                }

                var tempInt = (temp*10).toInt()
                bt[3] = tempInt.toByte()

                sendBleData(bt,object : BackData{
                    override fun callBackSuccess() {

                        WaitDialog.show(this@DetectionActivity,getString(R.string.waitHint))

                        Handler(Looper.getMainLooper()).postDelayed({

                            log("send获取含水量")
                            sendBleData(IntentKey.MEASURE_WATER,object : BackData{
                                override fun callBackSuccess() {
//                                    发送成功


                                    Handler(Looper.getMainLooper()).postDelayed({

                                                                                WaitDialog.dismiss()

                                    },3000)
                                }
                            })


                        }, 2000)

                    }
                })

            }
            binding.yangpinmingcheng->{
                showSelectDialog()
            }
        }
    }

    private fun sendBleData(bt: ByteArray,backData: BackData) {
        mClient!!.write(
            DataRepository.bleAddress, uuid1,uuid3,bt
        ) { code ->
            Log.d("data", "onResponse: "+code)
            if (code == REQUEST_SUCCESS) {
                backData.callBackSuccess()
            }else{
                toast(getString(R.string.bleFailToSend))
            }
        }
    }

    private interface BackData{
        fun callBackSuccess()

    }


    private fun showSelectDialog() {

        BottomMenu.show(arrayOf<String>(getString(R.string.class01), getString(R.string.class02), getString(R.string.class03),getString(R.string.class04)))
            .setOnMenuItemClickListener { dialog, text, index ->
//                toast(text.toString())
//2.设定样品类型
//01 06 05 02 01
//
//--01 06 ：帧头
//--05 ：帧长
//--02 ：设定样品类型
//--01 ：鸡肉（01为鸡肉，02为猪肉，03为牛肉，04为羊肉）

                var bt = IntentKey.SET_SAMPLE_TYPE
                bt[4] = (index+1).toByte()
                testId = index+1
                sendBleData(bt,object : BackData{
                    override fun callBackSuccess() {
                        binding.yangpinmingcheng.text = text.toString()
                    }
                })
                false
            }

    }


}
